<?php

namespace backend\controllers;

use backend\models\PrfScoreExchange;
use liangzoe\mobilesmser\TextSmser;
use Yii;
use backend\models\PayScoreItem;
use backend\models\PayScoreItemSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\LogUserScore;
use yii\db\ActiveRecord;
use yii\helpers\Url;
use yii\web\ForbiddenHttpException;

/**
 * PayScoreItemController implements the CRUD actions for PayScoreItem model.
 */
class PayScoreItemController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('pay-score-item')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all PayScoreItem models.
     * 产品兑换列表
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PayScoreItemSearch();
        $params = Yii::$app->request->queryParams; //数组
        $params['PayScoreItemSearch']['type'] = PrfScoreExchange::TYPE_PRODUCT;
        $dataProvider = $searchModel->search($params);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * 饮料兑换列表
     * @return string
     */
    public function actionDrink()
    {
        $searchModel = new PayScoreItemSearch();
        $params = Yii::$app->request->queryParams; //数组
        $params['PayScoreItemSearch']['type'] = PrfScoreExchange::TYPE_DRINK;

        if(!isset($params['PayScoreItemSearch']['logistics_state'])){
            $params['PayScoreItemSearch']['logistics_state'] = PayScoreItem::LOGISTICS_NO_SEND;
        }
        if(!isset($params['PayScoreItemSearch']['logTime'])){
            $params['PayScoreItemSearch']['logTime'] = date("Y-m-d");
        }
        $dataProvider = $searchModel->search($params);
        return $this->render('drink', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single PayScoreItem model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new PayScoreItem model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PayScoreItem();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing PayScoreItem model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
		$model_old = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
        	//发货
        	if(!empty($model->logistics_trade) && empty($model_old->logistics_trade)){
        		$model->logistics_state = '1';
        		$model->admin_uid = Yii::$app->user->identity->id;
        		$model->admin_time = time();
        		//快递信息订阅
        		$this->kuaidi($model->logistics_name,$model->logistics_trade);
        	}else{
        		$model->logistics_trade = $model_old->logistics_trade;//物流单号不给更改
        	}
        	//发货时间
        	if(!empty($model->send_time_1) && $model->send_time != strtotime($model->send_time_1)){
        		$model->send_time = (int)strtotime($model->send_time_1);
        	}
        	//送货时间
        	if(!empty($model->deliver_time_1) && $model->deliver_time != strtotime($model->deliver_time_1)){
        		$model->deliver_time = (int)strtotime($model->deliver_time_1);        		
        	}
        	
        	$model->save();      	
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
        	$kuaidi=ActiveRecord::findBySql("select code,`name` from grp_kuaidi where use_flag = 1")->asArray()->all();
        	$kuaidi[count($kuaidi)]=[
        	'code'=>'other',
        	'name'=>'其他快递'
        			];
        	if(!empty($model->send_time))  $model->send_time_1 = date('Y-m-d H:i:s',$model->send_time);
        	if(!empty($model->deliver_time))  $model->deliver_time_1 = date('Y-m-d H:i:s',$model->deliver_time);

            return $this->render('update', [
                'model' => $model,
            	'kuaidi' => $kuaidi
            ]);
        }
    }

    /**
     * Deletes an existing PayScoreItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PayScoreItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PayScoreItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PayScoreItem::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    public function actionAudit(){
    	$res = array('error'=>false,'msg'=>'');
    	if(\Yii::$app->user->can('pay-score-item-audit')){
     	
	    	$id = $_POST['id'];
	    	$type = $_POST['type'];
	    	$model = $this->findModel($id);
	    	
	    	$model->notes = trim($_POST['result']);
	    	if($type === '1'){//审核通过
	    		$model->audit_state = 1;   		
	    		$res['msg']='审核通过';
	    	}elseif($type === '0'){//审核不通过
	    		$model->audit_state = 2;
	    		$log = new LogUserScore();
	    		if($log->deleteLog($model->log_id, LogUserScore::STATE_EXCHANGE))
	    			$res['msg']='审核未通过';
	    		else
	    			$res['msg']='审核失败';
	    	}
	    	$model->save();
    	}else{
	    		$res['msg'] = 'Sorry , You don\'t have permission';
	    }
    	return json_encode($res);
    }

    /**
     * 兑换饮料发货
     * @return false|string
     * @throws NotFoundHttpException
     */
    public function actionSend(){
        $res = array('error'=>false,'msg'=>'');
        if(\Yii::$app->user->can('pay-score-item-send')){

            $id = $_POST['id'];
            $state = $_POST['state'];
            $model = $this->findModel($id);

            $model->notes = trim($_POST['result']);
            if($state === '1'){//发货
                $model->logistics_state = 1;
                $res['msg']='发货成功';
                $model->save();
                $sms = new TextSmser();
                $sms->sendSMS($model->logInfo->userInfo->tel, "您兑换的商品已经发货。请确认！");
            }
        }else{
            $res['msg'] = 'Sorry , You don\'t have permission';
        }
        return json_encode($res);
    }

    function kuaidi($logistics_name,$logistics_trade){
    	//调用快递订阅接口
    	if ($logistics_name!='other' && $logistics_trade != null)
    	{
//    		$url="https://poll.kuaidi100.com/poll";
			$url="http://www.kuaidi100.com/poll";
    		$param=[
    			'company'=>$logistics_name,
    			'number'=>$logistics_trade,
    			'key'=>'YjPgYUqw7427',
    			'parameters'=>[
    				'callbackurl'=>'http://www.'.Yii::$app->params['site_url'].Url::to(['callback/kuaidiscore']),
    				'resultv2'=>'1'
    			]
    		];
			
    		$post_data='schema=json&param='.json_encode($param,JSON_UNESCAPED_UNICODE);
    		$kuaidiRequestResult=self::curlRequest($url, $post_data);
    		$kuaidiRequestResult=json_decode($kuaidiRequestResult,true);
    		
    		if (!$kuaidiRequestResult['result'])
    		{
    				echo '快递订阅出错，原因：';
    				switch ($kuaidiRequestResult['returnCode'])
    				{
    					case '701':echo '拒绝订阅的快递公司';break;
    					case '700':echo '订阅方的订阅数据存在错误（如不支持的快递公司、单号为空、单号超长等）或错误的回调地址';break;
    					case '702':echo 'POLL:识别不到该单号对应的快递公司';break;
    					case '600':echo '您不是合法的订阅者（即授权Key出错）';break;
    					case '601':echo 'POLL:KEY已过期';break;
    					case '500':echo '服务器错误（即快递100的服务器出理间隙或临时性异常，有时如果因为不按规范提交请求，比如快递公司参数写错等，也会报此错误）';break;
    					case '501':echo '重复订阅';break;
    				}
    				print_r($kuaidiRequestResult);
    				return;
    			}
    		}
    }
    private static function curlRequest($url,$post_data)
    {
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    	$output = curl_exec($ch);
    	curl_close($ch);
    	return $output;
    }
}
